package com.ylr.gateway.config;

import com.ylr.base.common.enums.ResultEnum;
import com.ylr.base.common.tool.Result;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2023-05-01 10:32:43
 * className: SentinelConfig sentinel配置类
 * version: 1.0
 * description:
 */
@Configuration
public class SentinelConfig {

    public SentinelConfig() {
        // 设置gateway限流处理类
        GatewayCallbackManager.setBlockHandler(new GatewayBlockHandler());
    }

    /**
     * gateway限流处理类
     */
    private static class GatewayBlockHandler implements BlockRequestHandler {

        private static final Logger log = LoggerFactory.getLogger(GatewayBlockHandler.class);

        @Override
        public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
            log.warn("请求被限流了。message={} class={}", throwable.getMessage(), throwable.getClass().getName(), throwable);
            Result<Object> result = Result.getResult(ResultEnum.LIMIT_FAIL);
            return ServerResponse.ok().body(Mono.just(JSON.toJSONString(result)), String.class);
        }
    }
}
